import React, { useEffect, useState, useRef } from 'react'
import { List, Avatar, Image, Upload, message, Button, Space, Input, Modal, Popover, Row, Col } from 'antd';
import { DeleteTwoTone, PlusSquareTwoTone, EditTwoTone } from '@ant-design/icons';
import GoodsCascader from '../../../../components/GoodsCascader';
import axios from 'axios';
import moment from 'moment'
import { useNavigate } from 'react-router-dom'
export default function Index() {
    const navigate = useNavigate()
    const [listData, setListData] = useState([]);
    let changeInfo = { title: '', message: '', mytype: '', wanttype: '', createrid: JSON.parse(localStorage.getItem("loginUser")).id };
    let editChangeInfo = {};
    let loginUser = JSON.parse(localStorage.getItem("loginUser"));
    const [visible, setVisible] = useState(false);
    const [visible2, setVisible2] = useState(false);
    const [chaninfoId, setchaninfoId] = useState('');
    const titleRef = useRef()
    const messageRef = useRef()
    const titleRef2 = useRef()
    const messageRef2 = useRef()
    useEffect(() => {
        axios.get("http://localhost:8080/qryMyChange?id=" + loginUser.id).then(resp => {
            console.log(resp);
            if (resp.data.state === "0") {
                setListData(resp.data.data);
            }
        })
        return () => {
            //销毁组件时
            console.log('menu-destroy');
        };
    }, []);
    //创建交换的modal 确定后
    const handleOk = () => {
        message.destroy();
        changeInfo.title = titleRef.current.state.value;
        changeInfo.message = messageRef.current.resizableTextArea.textArea.value;

        if (changeInfo.title == '' || changeInfo.message == '' || changeInfo.mytype == '' || changeInfo.wanttype == '') {
            message.error("请填写完交换信息!")
            setTimeout(() => {
                navigate('userMenu/myChange/*')
            }, 200);

        } else {
            axios.post('http://localhost:8080/makeChange', changeInfo).then(resp => {
                if (resp.data.state === "0") {
                    message.success(resp.data.message, 1);
                    setTimeout(() => {
                        window.location.reload();
                    }, 500);
                }
            })
        }
    }

    //创建交换modal 取消
    const handleCancel = () => {
        setVisible(false)
    }
    const mytypeChange = (value) => {
        let lastIndex = value.length - 1
        let rs = value[lastIndex]
        console.log(rs);
        changeInfo.mytype = rs;
    }

    const wanttypeChange = (value) => {
        let lastIndex = value.length - 1
        let rs = value[lastIndex]
        console.log(rs);
        changeInfo.wanttype = rs;
    }

    const mytypeChange2 = (value) => {
        let lastIndex = value.length - 1
        let rs = value[lastIndex]

        console.log(rs);
        editChangeInfo.mytype = rs;
    }

    const wanttypeChange2 = (value) => {
        let lastIndex = value.length - 1
        let rs = value[lastIndex]
        console.log(rs);
        editChangeInfo.wanttype = rs;
    }
    const photoupdate = (info) => {
        if (info.file.status === 'done') {
            message.success(`${info.file.name}图片上传成功`);
            setTimeout(() => {
                window.location.reload()
            }, 500);
        } else if (info.file.status === 'error') {
            message.error(`图片上传失败,尝试更换另一张jpg图片`);
        }

    }
    const beforeUpload = (file) => {
        console.log(file.size);
        if (file.size > (2097152)) {
            console.log("图片超过2M");
            message.error(`图片不得超过2M`);
            return Upload.LIST_IGNORE;
        } else {
            return true;
        }
    }


    const deleteChange = (id) => {
        axios.post("http://localhost:8080/deleteChangeInfo?id=" + id).then(resp => {
            if (resp.data.state === "0") {
                message.success(resp.data.message, 1);
                setTimeout(() => {
                    window.location.reload()
                }, 800);
            }
        })
    }
    const makeChange = () => {
        setVisible(true);

    }
    const showModal = (id) => {   //修改物品信息的modal
        setVisible2(true);
        // editChangeInfo.id = id;
        setchaninfoId(id)
        titleRef2.current.state.value = '';
        messageRef2.current.resizableTextArea.textArea.value = '';
        console.log(editChangeInfo);
    };

    const handleOk2 = () => {
        editChangeInfo.title = titleRef2.current.state.value || null;
        editChangeInfo.message = messageRef2.current.resizableTextArea.textArea.value || null;
        editChangeInfo.id = chaninfoId;
        console.log("修改后物品信息:", editChangeInfo);
        axios.post("http://localhost:8080/updateChangeInfo", editChangeInfo).then(resp => {
            if (resp.data.state === "0") {
                message.success(resp.data.message, 1)
                setTimeout(() => {
                    window.location.reload()
                }, 1000);

            } else {
                message.error(resp.data.message, 1)
                setTimeout(() => {
                    window.location.reload()
                }, 1000);
            }

        }).catch(err => {
            message.error("请求超时!", 1);
            setTimeout(() => {
                window.location.reload()
                seteditVisible(false);
            }, 1000);
        })

    };
    const handleCancel2 = () => {
        setVisible2(false)
        titleRef2.current.state.value = '';
        messageRef2.current.state.value = '';
        setchaninfoId('')
        editChangeInfo = {}
    }
    return (
        <div className="animate__animated animate__fadeIn">
            <List
                itemLayout="vertical"
                size="large"
                pagination={{
                    onChange: page => {
                        console.log(page);
                    },
                    pageSize: 3,
                }}
                dataSource={listData}

                renderItem={item => (
                    <List.Item
                        key={item.id}
                        extra={
                            <Space direction="vertical">
                                <Popover placement="topLeft" content={'点击修改图片'}>
                                    <Upload maxCount={1} action={`http://localhost:8080/saveChangeInfoPhoto?id=${item.id}`} beforeUpload={beforeUpload} onChange={photoupdate}>
                                        <Image

                                            preview={false}
                                            width={135}
                                            height={135}
                                            src={`http://localhost:8080/getChangeInfoPhoto?id=${item.id}`}
                                        />
                                    </Upload>
                                </Popover>
                            </Space>
                        }
                    >
                        <List.Item.Meta
                            avatar={<Avatar src={`http://localhost:8080/getUserHead?id=${item.createrid}`} />}
                            title={`${item.title}`}
                            description={moment(Number(item.createtime)).format('YYYY-MM-DD HH:mm:ss')}
                        />
                        {item.message} <br />
                        <Space style={{ marginTop: 25 }}>
                            <Button icon={<EditTwoTone />} onClick={() => { showModal(item.id) }}>修改</Button>
                            <Button danger type="primary" onClick={() => { deleteChange(item.id) }}> 删除<DeleteTwoTone twoToneColor="red" /></Button>
                        </Space>

                    </List.Item>
                )}

            />
            <div style={{ position: 'fixed', right: 30, bottom: 20 }}>
                <Button onClick={makeChange} icon={<PlusSquareTwoTone width={100} />} style={{ width: 100, height: 40 }} type={'primary'}>创建</Button>
            </div>
            <Modal
                title="创建交换"
                visible={visible}
                onOk={handleOk}
                onCancel={handleCancel}
                // width={'30%'}
                centered={true}
            >
                <Row justify="center">
                    <Col>
                        <GoodsCascader style={{ width: '1.7REM', marginTop: '0.03REM' }} title="我的旧物类别" onChange={mytypeChange} />
                    </Col>
                </Row>
                <Row justify="center">
                    <Col>
                        <GoodsCascader title="想要的类别" style={{ width: '1.7REM', marginTop: '0.03REM' }} onChange={wanttypeChange} />
                    </Col>
                </Row>
                <Row justify="center">
                    <Col>
                        <Input placeholder="创建标题" style={{ width: '1.7REM', marginTop: '0.03REM' }} ref={titleRef}></Input>
                    </Col>
                </Row>
                <Row justify="center">
                    <Col>
                        <Input.TextArea placeholder="具体描述" style={{ width: '1.7REM', marginTop: '0.03REM' }} ref={messageRef} />
                    </Col>
                </Row>

            </Modal>

            <Modal
                title="修改信息"
                visible={visible2}
                onOk={handleOk2}
                onCancel={handleCancel2}
                // width={'30%'}
                centered={true}
            >
                <Row justify="center">
                    <Col>
                        <GoodsCascader title="我的旧物类别" style={{ width: '1.7REM', marginTop: '0.03REM' }} onChange={mytypeChange2} />
                    </Col>
                </Row>
                <Row justify="center">
                    <Col>
                        <GoodsCascader title="想要的类别" style={{ width: '1.7REM', marginTop: '0.03REM' }} onChange={wanttypeChange2} />
                    </Col>
                </Row>
                <Row justify="center">
                    <Col>
                        <Input placeholder="创建标题" style={{ width: '1.7REM', marginTop: '0.03REM' }} ref={titleRef2}></Input>
                    </Col>
                </Row>
                <Row justify="center">
                    <Col>
                        <Input.TextArea style={{ width: '1.7REM', marginTop: '0.03REM' }} placeholder="具体描述" ref={messageRef2} />
                    </Col>
                </Row>
            </Modal>
        </div>
    )
}